package httpHandler

import (
	"crypto/md5"
	"encoding/hex"
	"gitee.com/zaiqiang231/lovesport-user-service/app/config"
	"github.com/gin-gonic/gin"
	"io"
	"net/http"
	"os"
	"path"
)

type SysUploadHandler struct {
}

func (*SysUploadHandler) UploadPicture(c *gin.Context) {
	_, header, err := c.Request.FormFile("file")
	if err != nil {
		WriteResponse(c, http.StatusBadRequest, err.Error(), nil)
		return
	}

	// 尝试创建此路径
	err = os.MkdirAll(config.GlobalAppConfig.UploadConfig.PictureStorePath, os.ModePerm)
	if err != nil {
		WriteResponse(c, http.StatusInternalServerError, err.Error(), nil)
		return
	}
	extName := path.Ext(header.Filename)
	file, errFile := header.Open()
	if errFile != nil {
		WriteResponse(c, http.StatusInternalServerError, errFile.Error(), nil)
		return
	}
	hash := md5.New()
	_, err = io.Copy(hash, file)
	if err != nil {
		WriteResponse(c, http.StatusInternalServerError, err.Error(), nil)
		return
	}
	saveFileName := hex.EncodeToString(hash.Sum(nil)) + extName

	err = c.SaveUploadedFile(header, config.GlobalAppConfig.UploadConfig.PictureStorePath+saveFileName)
	if err != nil {
		WriteResponse(c, http.StatusInternalServerError, err.Error(), nil)
		return
	}
	WriteResponse(c, 0, "success", gin.H{
		"url": config.GlobalAppConfig.UploadConfig.PicturePath + saveFileName,
	})
}
